/* eslint-disable no-underscore-dangle */
import { ApiBridge } from "../assets/scripts/pkg/rust_api_proxy";

const API_SECRET = 'ac2708671fa53e7d5e2d4b6514c92d85bcfa0c6469332f51ea6e366ec10e356a8e4705b38777c6031ddc0717fd16ae4a38495df1fffef7c603b2684a09662c4b89b2d63f7ed59fcd2b507c11338cc4f4915c1e728c3222ca17709ad0e81ab21958bcb624d4736f8c26916fa732a1f939e0e2dcd35f629d9f504afc7476328d86394dd374c6a4be8671e84d135cf7f8c38a3d36df3a71d3d8ea541baa7738c5946937a12a15b6928ff97c71e3c799b7c361df76aa4407d4092990395c17f60a731e2bd557718270b24a03528c88b4f441401552aaaed72c56b4299ca220f049d75d6e53e38c000164d071f7739106bf985e53670e23f88e71da09a03c803ac9203166b73f371d3c579b23d3d5eae60b0d5783d1c7cff5d487f867c0c17818967bf5ec9ef0435a79f1d3ba3170a9428a63'


type importedType = typeof import('../assets/scripts/pkg/rust_api_proxy')

export async function useApiProxy(): Promise<ApiBridge> {
    // @ts-ignore
    if (window.__ApiProxyInstance) return window.__ApiProxyInstance

    const instance: importedType = await import('../assets/scripts/pkg/rust_api_proxy')
    const inited = new instance.ApiBridge(API_SECRET);
    // @ts-ignore
    window.__ApiProxyInstance = inited

    return inited
}

interface ResponseOfProxy<D = any> {
    code: string,
    data?: D,
    msg?: string,
    responseId?: string
}


/**
 * 调用微服务平台
 * @param apiName 接口地址，无需带 / 前缀
 * @param data 请求数据
 * @param method 请求方法
 * @returns 
 */
export async function invokeMicroProxy<T = any>(apiName: string, data: any, method = 'POST'): Promise<ResponseOfProxy<T>> {
    const instance = await useApiProxy()
    let data_raw: string
    if (typeof data == "string") {
        data_raw = data
    }
    else {
        try {
            data_raw = JSON.stringify(data)
        } catch (e) {
            return {
                code: "1",
                msg: "data数据无法被JSON序列化"
            }
        }
    }

    return instance.invoke_micro(apiName, data_raw, method)
}

/**
 * 调用旧接口平台
 * @param service 服务名
 * @param data 请求数据
 * @param version 版本号，默认1.0
 */
export async function invokeOpenProxy<T = any>(service: string, data: any, version = "1.0"): Promise<ResponseOfProxy<T>> {
    const instance = await useApiProxy()
    let data_raw: string
    if (typeof data == 'string') data_raw = data
    else {
        try {
            data_raw = JSON.stringify(data)
        } catch (e) {
            return {
                code: "1",
                msg: "data数据无法被JSON序列化"
            }
        }
    }
    return instance.invoke_open(service, data_raw, version)
}